package org.jon.lagoon.controller;

import org.jon.lagoon.model.User;
import org.jon.lagoon.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import java.util.Map;

/**
 * Created by Jon on 2017/9/26.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public User registerUser(User user) {// @RequestBody 是用来接收 json 格式字符串
        return userService.save(user);
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String username, String password) throws ServletException {
        /*if (json.get("username") == null || json.get("password") == null) {
            throw new ServletException("Please fill in username and password");
        }
        String userName = json.get("username");
        String password = json.get("password");*/

        User user = userService.findByUserName(username);
        if (user == null) {
            throw new ServletException("User name not found.");
        }
        String pwd = user.getPassword();
        if (!pwd.equals(password)) {
            throw new ServletException("Invalid login.Please check your name or password.");
        }
        return "login success!";

    }



    @RequestMapping("/test")
    public String test() {
        return "hello test!";
    }

}
